package com.valuegroup.smarttodo.ui.programme.weekplan;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarLayout;
import com.haibin.calendarview.CalendarView;
import com.valuegroup.smarttodo.R;
import com.valuegroup.smarttodo.common.BaseViewHolder;
import com.valuegroup.smarttodo.common.CommonRecyclerAdapter;
import com.valuegroup.smarttodo.data.ServiceFactory;
import com.valuegroup.smarttodo.data.model.AppStatus;
import com.valuegroup.smarttodo.data.model.Task;
import com.valuegroup.smarttodo.data.vo.CalendarQueryParams;
import com.valuegroup.smarttodo.data.vo.WeekPlanEventVo;
import com.valuegroup.smarttodo.ui.BaseActivity;
import com.valuegroup.smarttodo.ui.programme.curriculum.CurriculumOrderActivity;
import com.valuegroup.smarttodo.ui.programme.goals.detail.GoalsDetailActivity;
import com.valuegroup.smarttodo.ui.todo.task.detail.TaskDetailActivity;
import com.valuegroup.smarttodo.plugins.pickdialog.DateUtils;
import com.valuegroup.smarttodo.util.AlertUtils;

import java.util.Date;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.PopupMenu;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 事务排期
 */
public class WeekArrangeActivity extends BaseActivity implements
        CalendarView.OnCalendarSelectListener,
        CalendarView.OnYearChangeListener {

    @BindView(R.id.tv_month_day)
    TextView mTextMonthDay;
    @BindView(R.id.tv_year)
    TextView mTextYear;
    @BindView(R.id.tv_lunar)
    TextView mTextLunar;
    @BindView(R.id.tv_current_day)
    TextView mTextCurrentDay;
    @BindView(R.id.calendarView)
    CalendarView mCalendarView;
    @BindView(R.id.rl_tool)
    RelativeLayout mRelativeTool;

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    @BindView(R.id.calendarLayout)
    CalendarLayout mCalendarLayout;

    @BindView(R.id.layoutFilter)
    LinearLayout layoutFilter;
    @BindView(R.id.labFilter)
    TextView labFilter;
    @BindView(R.id.editSearch)
    EditText editSearch;
    @BindView(R.id.layoutSearch)
    LinearLayout layoutSearch;
    @BindView(R.id.btnGoFind)
    ImageView btnGoFind;
    @BindView(R.id.tagOpenFilter)
    ImageView tagOpenFilter;

    private WeekArrangeAdapter adapter;
    private PopupMenu filterMenu;
    private int mYear;
    private int countSize = 0;
    private CalendarQueryParams queryParams;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_week_arrange);
        ButterKnife.bind(this);

        queryParams = CalendarQueryParams.getDefaultParams();

        intiCalendar();
        initRecyclerView();
        initData();
    }

    @SuppressLint("SetTextI18n")
    private void intiCalendar() {
        //setStatusBarMode();

        mTextMonthDay = findViewById(R.id.tv_month_day);
        mTextYear = findViewById(R.id.tv_year);
        mTextLunar = findViewById(R.id.tv_lunar);
        mRelativeTool = findViewById(R.id.rl_tool);
        mCalendarView = findViewById(R.id.calendarView);
        mTextCurrentDay = findViewById(R.id.tv_current_day);
        mTextMonthDay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mCalendarLayout.isExpand()) {
                    mCalendarLayout.expand();
                    return;
                }
                mCalendarView.showYearSelectLayout(mYear);
                mTextLunar.setVisibility(View.GONE);
                mTextYear.setVisibility(View.GONE);
                mTextMonthDay.setText(String.valueOf(mYear));
            }
        });
        findViewById(R.id.fl_current).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCalendarView.scrollToCurrent();
            }
        });
        mCalendarView.setOnCalendarSelectListener(this);
        mCalendarView.setOnYearChangeListener(this);
        mTextYear.setText(String.valueOf(mCalendarView.getCurYear()));
        mYear = mCalendarView.getCurYear();
        Date day = DateUtils.getDate(mCalendarView.getCurYear(), mCalendarView.getCurMonth(), mCalendarView.getCurDay(), 0, 0);
        queryParams.setFindDay(day);
        mTextMonthDay.setText("第" + DateUtils.getWeekOfYear(day) + "周\n" + mCalendarView.getCurMonth() + "月" + mCalendarView.getCurDay() + "日");
        mTextLunar.setText("今日");
        mTextCurrentDay.setText(String.valueOf(mCalendarView.getCurDay()));

    }

    protected void initRecyclerView() {

        filterMenu = new PopupMenu(this, layoutFilter);
        filterMenu.inflate(R.menu.menu_week_plan_evnet_filter);
        filterMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                // 全部0；已选1；未选0
                switch (item.getItemId()) {
                    case R.id.m1:
                        queryParams.setFilterType(0);
                        break;
                    case R.id.m2:
                        queryParams.setFilterType(1);
                        break;
                    case R.id.m3:
                        queryParams.setFilterType(2);
                        break;
                }

                // 更新list列表
                refreshAllData(false);

                // 获取item数量
                labFilter.setText(String.format(getResources().getString(R.string.week_plan_event_filter), item.getTitle(), countSize));
                return true;
            }
        });


        editSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                    System.out.println("查询数据onEditorAction");
                    queryParams.setSearchKey(v.getText().toString());
                    refreshAllData(true);
                }
                // 返回true，保留软键盘。false，隐藏软键盘
                return true;
            }
        });


        editSearch.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                if (hasFocus) {
                    // 得到焦点

                    // 光标移动到末尾
                    editSearch.setSelection(editSearch.getText().length());

                    // 弹出键盘
                    InputMethodManager inputManager = (InputMethodManager) editSearch.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputManager.showSoftInput(editSearch, 0);
                }
            }
        });

        editSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (!TextUtils.isEmpty(charSequence.toString())) {
                    queryParams.setSearchKey(charSequence.toString());
                    refreshAllData(true);
                }
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        assert recyclerView != null;
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        adapter = new WeekArrangeAdapter(this, loadData());
        recyclerView.setAdapter(adapter);
    }

    protected void initData() {
        updateFilterLab();
    }

    private void updateFilterLab() {
        // 更新过滤标签
        String str = getResources().getString(R.string.week_plan_event_filter);
        if (DateUtils.compareDate(queryParams.getFindDay(), new Date()) < 0) {
            // 过去的日期中只能查询已选内容
            labFilter.setText(String.format(str, filterMenu.getMenu().findItem(R.id.m2).getTitle(), countSize));
            tagOpenFilter.setVisibility(View.GONE);
        } else {
            labFilter.setText(String.format(str, filterMenu.getMenu().getItem(queryParams.getFilterType()).getTitle(), countSize));
            tagOpenFilter.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 更新列表所有数据
     */
    private void refreshAllData(boolean doSearch) {
        if (!doSearch) {
            queryParams.setSearchKey(null);
        }

        // 刷新列表数据
        adapter.refreshListData(loadData());
        // 平移到相关位置
        recyclerView.smoothScrollToPosition(0);
    }

    private List<WeekPlanEventVo> loadData() {
        List<WeekPlanEventVo> data = ServiceFactory.getInstance().getEventService().findEvent(queryParams);
        countSize = data.size();
        updateFilterLab();
        return data;
    }

    @Override
    public void onBackPressed() {
        setCloseParams();
        super.onBackPressed();
    }

    private void setCloseParams() {
        Intent intent = new Intent();
        setResult(RESULT_OK, intent);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        refreshAllData(false);
    }


    @Override
    public void onCalendarOutOfRange(Calendar calendar) {

    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onCalendarSelect(Calendar calendar, boolean isClick) {
        mTextLunar.setVisibility(View.VISIBLE);
        mTextYear.setVisibility(View.VISIBLE);

        Date day = DateUtils.getDate(calendar.getYear(), calendar.getMonth(), calendar.getDay(), 0, 0);
        mTextMonthDay.setText("第" + DateUtils.getWeekOfYear(day) + "周\n" + calendar.getMonth() + "月" + calendar.getDay() + "日");
        mTextYear.setText(String.valueOf(calendar.getYear()));
        mTextLunar.setText(calendar.getLunar());
        mYear = calendar.getYear();

        queryParams.setFindDay(day);
        refreshAllData(false);
    }

    @Override
    public void onYearChange(int year) {
        mTextMonthDay.setText(String.valueOf(year));
    }

    @OnClick({R.id.layoutFilter, R.id.btnGoFind, R.id.imgbtn_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layoutFilter:
                // 过去的日期中只能查询已选内容
                if (DateUtils.compareDate(queryParams.getFindDay(), new Date()) < 0) {
                    return;
                }

                filterMenu.show();
                break;
            case R.id.imgbtn_back:
                finishAfterTransition();
                break;
            case R.id.btnGoFind:
                if (View.GONE == layoutFilter.getVisibility()) {
                    layoutFilter.setVisibility(View.VISIBLE);
                    layoutSearch.setVisibility(View.GONE);

                    btnGoFind.setImageResource(R.drawable.ic_find_gray3);

                    // 恢复全部数据
                    refreshAllData(false);
                } else {
                    layoutFilter.setVisibility(View.GONE);
                    layoutSearch.setVisibility(View.VISIBLE);
                    editSearch.setText(null);
                    btnGoFind.setImageResource(R.drawable.ic_close_gray3);

                    /**
                     * 动态给EditText获得焦点并弹起软键盘
                     */
                    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
                    editSearch.setFocusable(true);
                    editSearch.setFocusableInTouchMode(true);
                    editSearch.requestFocus();
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.showSoftInput(editSearch, 0);
                }
                break;
            /*case R.id.btnGoTimeLine:
                // 事务列表
                Intent intent = new Intent(view.getContext(), WeekTimelineActivity.class);
                //intent.putExtra(PARAMS_KEY, DATA.getId());
                //intent.putExtra(PARAMS_POSITION, DATA_POSITION);
                startActivityForResult(intent, 1001);

                break;*/
        }
    }

    class WeekArrangeAdapter extends CommonRecyclerAdapter<WeekPlanEventVo> {


        public WeekArrangeAdapter(Context context, List<WeekPlanEventVo> data) {
            super(context, data);
            setMainLayoutId(R.layout.item_week_arrange);
            setBottomLayoutId(R.layout.item_default_bottom);
        }

        @Override
        public void bindHeadView(BaseViewHolder v, int position) {

        }

        @Override
        public void bindBottomView(BaseViewHolder v, int position) {

        }

        @Override
        public void bindMainView(BaseViewHolder v, int position) {
            WeekPlanEventVo data = getData(position);

            // 添加与移除习惯关联
            TextView btnOperation = v.getView(R.id.btnOperation);
            btnOperation.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (data.isJoinSchedule()) {
                        AlertUtils.removeJoinDialog(getmContext(), String.format(getResources().getString(R.string.alt_remove_week_plan_event_join), data.getTitle()), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                data.setJoinSchedule(false);
                                data.setJoinScheduleDt(null);
                                data.setScheduleDt(null);
                                data.setScheduleWeekNum(0);
                                changeBtnOperationView(v, false);
                                ServiceFactory.getInstance().getEventService().doRmoveJoinScheduleDelTask(data.getId());
                            }
                        });

                    } else {
                        data.setJoinSchedule(true);
                        data.setJoinScheduleDt(new Date());
                        data.setScheduleDt(queryParams.getFindDay());
                        data.setScheduleWeekNum(DateUtils.getYearWeekNumber(queryParams.getFindDay()));
                        changeBtnOperationView(v, true);
                        ServiceFactory.getInstance().getEventService().doJoinScheduleAndCreateTask(data.getId(), queryParams.getFindDay());
                    }
                }
            });

            // 初始化内容
            v.setImageResource(R.id.tagEmoji, (data.getEventType() == AppStatus.EventType.STUDY) ? R.drawable.ic_study_gray3 : R.drawable.ic_event_gray3);
            ((ImageView) v.getView(R.id.tagEmoji)).setColorFilter(ContextCompat.getColor(getmContext(), (data.getEventType() == AppStatus.EventType.STUDY) ? R.color.colorAccent : R.color.colorLink));
            v.setText(R.id.labTitle, data.getTitle());
            v.setText(R.id.labTime, String.format(getmContext().getResources().getString(R.string.lab_minute), data.getPreMinute()));
            switch (data.getEventType()) {
                case AppStatus.EventType.STUDY:
                    v.setText(R.id.labEventType, "学习");
                    break;
                case AppStatus.EventType.GOALS_MONTH:
                    v.setText(R.id.labEventType, "本月度");
                    break;
                case AppStatus.EventType.GOALS_QUARTER:
                    v.setText(R.id.labEventType, "本季度");
                    break;
                case AppStatus.EventType.GOALS_YEAR:
                    v.setText(R.id.labEventType, "本年度");
                    break;
            }

            v.getView(R.id.btnGoDetail).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (data.isJoinSchedule()) {
                        // 已排期查看任务详情
                        Task t = ServiceFactory.getInstance().getEventService().findEventTask(data.getId());
                        if (t != null) {
                            Intent intent = new Intent(getmContext(), TaskDetailActivity.class);
                            intent.putExtra(TaskDetailActivity.PARAMS_KEY, t.getId());
                            startActivityForResult(intent, 1005);
                        }
                    } else {
                        // 未排期查看数据来源
                        if (data.getEventType() > AppStatus.EventType.LINE_STUDY && data.getEventType() < AppStatus.EventType.LINE_GOALS) {
                            Intent intent = new Intent(v.getContext(), CurriculumOrderActivity.class);
                            intent.putExtra(CurriculumOrderActivity.PARAMS_KEY, data.getSourceId());
                            startActivityForResult(intent, 1006);
                        } else if (data.getEventType() > AppStatus.EventType.LINE_GOALS) {
                            Intent intent = new Intent(v.getContext(), GoalsDetailActivity.class);
                            intent.putExtra(GoalsDetailActivity.PARAMS_KEY, data.getSourceId());
                            startActivityForResult(intent, 1006);
                        }
                    }
                }
            });

            changeBtnOperationView(v, data.isJoinSchedule());

            // 过去的日期且已完成事务不显示操作按钮
            if (data.getFinish()) {
                v.setViewVisibility(R.id.btnOperation, (DateUtils.compareDate(queryParams.getFindDay(), new Date()) >= 0));
            } else {
                v.setViewVisibility(R.id.btnOperation, true);
            }
            // 完成状态
            v.setViewVisibility(R.id.tagFinish, data.getFinish());
        }

        private void changeBtnOperationView(BaseViewHolder v, boolean isJoinSchedule) {
            // 变更操作按钮视图内容
            v.setTextAndColor(R.id.btnOperation,
                    getResources().getString(isJoinSchedule ? R.string.op_remove : R.string.op_join),
                    ContextCompat.getColor(getmContext(), isJoinSchedule ? R.color.colorWarn : R.color.colorLink));
        }

        @Override
        public void bindAppendView(BaseViewHolder v, int position) {

        }

    }

}
